package com.jvyou.subject.infra.basic.script;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * Druid 配置加密脚本
 *
 * @author 橘柚
 * @since 2024/9/25 22:24
 */
public class DruidEncryptScript {

    // 公钥
    private static final String publicKey;
    // 私钥
    private static final String privateKey;

    static {
        try {
            // 利用 ConfigTools 生成 公钥和私钥
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println("私钥：" + privateKey);
            publicKey = keyPair[1];
            System.out.println("公钥：" + publicKey);
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 加密
     *
     * @param plainText 明文
     * @return 密文
     * @throws Exception 错误
     */
    public static String encrypt(String plainText) throws Exception {
        return ConfigTools.encrypt(privateKey, plainText);
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @return 明文
     * @throws Exception 错误
     */
    public static String decrypt(String cipherText) throws Exception {
        return ConfigTools.decrypt(publicKey, cipherText);
    }

    public static void main(String[] args) throws Exception {

    }
}
